<template>
	<view>
		<!-- 未正常绑定 -->
		<view class="bind-error" v-if="data.isband">
			<uv-icon name="error-circle" color="#fc4631" size="40"></uv-icon>
			<view class="red">{{ data.bindError }}</view>
			<view class="tips" v-if="data.otherName">已绑定商户：{{ data.otherName }}</view>
		</view>
		
		<!-- 心跳检测到视频中断或异常 -->
		<view class="bind-error" v-else-if="data.heartError.show">
			<uv-icon name="error-circle" color="#fc4631" size="40"></uv-icon>
			<view class="red">{{ data.heartError.msg }}</view>
		</view>
		
		<!-- 正常绑定 -->
		<view class="pageBox" v-else>
			<uv-image :src="data.liveInfo?.material_cover_full_url" width="100%" height="300rpx" mode="widthFix" v-if="data.showStartBtn" />
			<view id="mui-player" v-show="!data.showStartBtn"></view>
			<view class="live-info">
				<view class="name">{{data.liveInfo?.live_name}}</view>
				<view class="time">{{data.liveInfo?.start_time}}</view>
				<view class="tips" v-if="data.showStartBtn">
					<uv-icon name="warning" size="22" color="#63a103" />
					<view>{{data.liveInfo?.tip_message}}</view>
				</view>
			</view>
			<view class="btmTips" @click="startPlay" v-if="data.showStartBtn && data.liveInfo.playback_activity_flag">观看回放</view>
		</view>
		
		<uv-modal ref="MoverTime" title="回放播放完毕" :closeOnClickOverlay="false">
			<template v-slot:confirmButton>
				<view class="modal-btn">
					<view class="btn" @click="playAgain">再次观看</view>
				</view>
			</template>
		</uv-modal>
		<uv-toast ref="toastLayer"></uv-toast>
		
	</view>
</template>


<script setup>
	import 'mui-player/dist/mui-player.min.css'
	import MuiPlayer from 'mui-player';
	import Hls from 'hls.js'
	import { bindLive, merchantDetail, getlive, heartbeat, liveCheck, } from '@/api';
	
	const toastLayer = ref(null);
	const MoverTime = ref(null);
	const data = reactive({
		showCover: true,
		liveNo: null,
		companyCode:null,
		mid:null,
		merchan:{},
		isband: false,//绑定异常
		otherName:null,
		mp:null,
		showStartBtn: true,
		liveInfo:{},
		heartError: { //心跳异常情况处理
			show: false,
			msg: ''
		},
	})
	onLoad((option) => {
		data.companyCode = option.company_code
		data.liveNo = option.live_no
		data.mid = option.mid
		uni.showLoading()
		bindLiveUser()
		// getLiveDetail()
	})
	//绑定
	const bindLiveUser = () => {
		const params = {
			openid: uni.getStorageSync('openid'),
			live_no: data.liveNo,
			mid: data.mid
		}
		bindLive(params).then(res => {
			uni.hideLoading()
			if(res.code === 200001){
				uni.setStorageSync('token',res.data.access_token)
				uni.setStorageSync('mid',data.mid)
				uni.setStorageSync('companyCode',data.companyCode)
				getMerchant()
				getLiveDetail()
			}else if(res.code > 500213){
				data.isband = true
				data.bindError = res.message
			}else if(res.code === 500212){
				data.bindError = '您已绑定其他用户，无法再绑定该用户！'
				data.isband = true
				data.otherName = res.data.merchant_name
			}else if(res.code === 400200){
				// 异常抛出
			}else{
				toastLayer.value.show({ type: 'error',message: res.message})
			}
		}).catch(error => {
			console.error('绑定直播失败:', error);
		});
	}
	const getMerchant = () => {
		merchantDetail({mid: data.mid}).then(res => {
			data.merchan = {
				id: res.data.id,
				nickname: res.data.nickname,
				phone: res.data.phone,
				company_user_id: res.data.company_user_id
			}
		})
	}
	//直播信息
	const getLiveDetail = ()=> {
		getlive({live_no: data.liveNo}).then(res => {
			if(res.code == 200001){
				data.liveInfo = res.data
				if(data.liveInfo.status == 0){
					//未开始
				}else if(data.liveInfo.status == 1){
					//直播中
					initPlayer()
				}else if(data.liveInfo.status == 2){
					//已结束
					initPlayer()
				}
			}else{
				toastLayer.value.show({
					type: 'error',
					title: '默认主题',
					message: res.message
				})
			}
		}).catch(error => {
			const params = {type: 'error',message: error}
			toastLayer.value.show({params})
		});
	}
	//初始化播放器
	const initPlayer = () => {
		data.mp = new MuiPlayer({
			container:'#mui-player',
			src: data.liveInfo.material_video_full_url,
			parse:{
				type: 'hls',
				loader: Hls,
				autoplay: false,
			}
		})
		let videoTag = document.getElementsByTagName('video')[0]
		videoTag.setAttribute('webkit-playsinline', 'true');
		videoTag.setAttribute('playsinline', 'true');
		nextTick(() => {
			data.mp.on('ready', function(event) {
				let _video = data.mp.video();
				_video.addEventListener("play", function(e) {
					intervalId = setInterval(getHeartbeat, 5000);// 播放心跳,每5秒更新一次时间
					interCheck = setInterval(getLiveCheck, 30000);//检查心跳,每5分钟更新一次时间
					console.log('video play')
				});
				_video.addEventListener("pause", function(e) {
					console.log('video pause')
					clearInterval(intervalId);
					clearInterval(interCheck);
				});
				_video.addEventListener("ended", function(e) {
					MoverTime.value.open();
					data.mp.destroy();
					clearInterval(intervalId);
					clearInterval(interCheck);
				});
			});
		})
	}
	let intervalId	//播放心跳定时器
	let interCheck	//检查心跳定时器
	//开启播放
	const startPlay = ()=> {
		data.showStartBtn = false
		data.mp.video().play()
	}
	//播放心跳
	const getHeartbeat = ()=> {
		heartbeat({
			live_no: data.liveNo,
			live_status:data.liveInfo.status,
			live_id: data.liveInfo.live_id,
			merchant_info: data.merchan
		}).then(res => {
			if(res.code === 400203){//视频下架
				showToast(res.message)
			}
		}).catch(error => {
			showToast(error)
		});
	}
	const getLiveCheck = () => {
		liveCheck({live_no: data.liveNo}).then(res => {
			//处理异常抛出:直播间下架/用户禁用/商户是否存在
			if(res.data.err_flag > 0){
				data.heartError.show = true
				data.heartError.msg = res.data.msg
				data.mp.destroy();
				clearInterval(intervalId);
				clearInterval(interCheck);
			}
		})
	}
	const showToast = (msg)=> {
		const params = {
			type: 'error',
			title: '默认主题',
			message: msg,
		}
		toastLayer.value.show({
			...params
		})
	}
	const showModal = ()=> {
		MoverTime.value.open();
	}
	const playAgain = ()=> {
		data.mp.video().play()
		MoverTime.value.close();
	}
</script>

<style lang="scss" scoped>
	page{background-color: #f1f1f1;}
	.pageBox {padding: 0;height: 100%;display: flex;flex-flow: column nowrap;
		.live-info{color: #333;padding: 40rpx;line-height: 60rpx;
			.name{font-size: 36rpx;font-weight: 600;}
			.time{font-size: 24rpx;}
			.tips{font-size: 28rpx;color: #63a103;margin-top: 40rpx;display: flex;}
		}
		.btmTips{position: fixed;bottom: 0;left: 0;width: 100vw;background: #ef4636;text-align: center;padding: 40rpx 0 50rpx;color: #fff;
		 span:first-child{margin-right: 10rpx;}
		}
		.btn-group{position: fixed;bottom: 0;left: 0;width: 100vw;display: flex;
			.btn{border: 1px solid #ef4636;color: #ef4636;margin: 30rpx;line-height: 72rpx;width: 50%;text-align: center}
			.red{color: #fff;background: #ef4636;}
		}
	}
	.modal-btn{display: flex;justify-content: space-around;border-top: 1px solid #eee;margin-top: -20rpx;padding: 40rpx;
		.btn{color: #ef4636;}
	}
	.bind-error {
		text-align: center;
		padding-top: 15vh;
	
		.uv-icon {
			justify-content: center;
			margin-bottom: 60rpx;
		}
	
		.red {
			color: #fc4631;
		}
	
		.tips {
			font-size: 26rpx;
			padding: 50rpx 0;
		}
	}
</style>